package org.jetnuke.modules.weblinks;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.LinkLinkDAO;
import org.jetnuke.dao.LinkVoteDataDAO;
import org.jetnuke.entities.LinksVoteData;

public class Comments implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Comments.class);

	int lid;

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		LinkLinkDAO ddm = DataAccessDriver.getInst().newLinkLinkDAO();
		vc.put("link", ddm.retrieveByPK(lid));
		HashMap totalVotesMap = new HashMap();
		HashMap averageVotesMap = new HashMap();
		LinkVoteDataDAO dvdm = DataAccessDriver.getInst().newLinkVoteDataDAO();
		List ls = dvdm.selectWithComment(lid);
		vc.put("comments", ls);
		Iterator it = ls.iterator();
		while (it.hasNext()) {
			LinksVoteData vote = (LinksVoteData) it.next();
			String user = vote.getRATINGUSER();
			if (user != null && user.length() > 0) {
				Iterator it2 = dvdm.getByRatingUser(user).iterator();

				int sum = 0;
				int count = 0;
				while (it2.hasNext()) {
					LinksVoteData user_vote = (LinksVoteData) it2.next();
					count++;
					sum += user_vote.getRATING();
				}
				if (count > 0) {
					totalVotesMap.put(vote, new Integer(count));
					averageVotesMap.put(vote,
							new Double(sum / ((double) count)));
				}
			}
		}
		vc.put("totalVotesMap", totalVotesMap);
		vc.put("averageVotesMap", averageVotesMap);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

	public void setLid(int lid) {
		this.lid = lid;
	}
}
